var path = require('path')
var url = require('url');
var remote = require('electron').remote;
var storage = remote.require('electron-storage');
const dialog = remote.dialog;
var api = require('./api.js');

var login = function() {
    console.log("login...");

    var u = document.getElementById('username').value;
    var p = document.getElementById('password').value;
    if (!u || !p) {
        return;
    }

    console.log("login username:" + u + " password:" + p);
    api.login(u, p)
        .then((r) => {
            console.log("login success:", r, r.api_token);
            var obj = {
                accessToken:r.api_token, 
                gobelieveToken:r.im_token, 
                uid:r.im_uid, 
                username:u
            };
            api.accessToken = r.api_token;
            return Promise.all([api.getProfile(), obj]);
        })
        .then((values) => {
            console.log("values:", values);

            var p = values[0];
            var obj = values[1];
            obj = Object.assign(obj, p);
            obj.name = p.nickname;
            obj.avatar = p.portrait;
            storage.set("token.json", obj, (err)=> {
                window.location.assign("index.html");
            });  
        })
        .catch((err) => {
            console.log("login failure:", err);
            dialog.showErrorBox("登录失败", "用户名和密码错误");
        });
}

$(document).ready(function() {

});
